import { onLoad } from '@dcloudio/uni-app'
import { needLoginPages as _needLoginPages, getNeedLoginPages, isTableBar } from '@/utils'
import { checkTokenIsValid } from '@/utils/token'

const loginRoute = import.meta.env.VITE_LOGIN_URL
const isDev = import.meta.env.DEV
const isLogined = async () => {
  return await checkTokenIsValid()
}
// 检查当前页面是否需要登录
export function usePageAuth() {
  onLoad(async (options) => {
    // 获取当前页面路径
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const currentPath = `/${currentPage.route}`

    // 获取需要登录的页面列表
    let needLoginPages: string[] = []
    if (isDev) {
      needLoginPages = getNeedLoginPages()
    } else {
      needLoginPages = _needLoginPages
    }
    // console.log('needLoginPages', needLoginPages)

    // 检查当前页面是否需要登录
    const isNeedLogin = needLoginPages.includes(currentPath)
    // console.log('当前页面是否需要登录', isNeedLogin)
    if (!isNeedLogin) {
      return
    }

    const hasLogin = await isLogined()
    // console.log('当前页面是否已经登录', hasLogin)
    if (hasLogin) {
      return true
    }

    // 构建重定向URL
    const queryString = Object.entries(options || {})
      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
      .join('&')

    const currentFullPath = queryString ? `${currentPath}?${queryString}` : currentPath
    const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(currentFullPath)}`
    // console.log('重定向到登录页', redirectRoute)
    // 重定向到登录页
    if (isTableBar(loginRoute)) {
      uni.switchTab({ url: loginRoute })
    } else {
      uni.redirectTo({ url: redirectRoute })
    }
  })
}
